<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="租户列表">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <div class="moss-custom-table-param">
        <n-grid x-gap="12" :cols="2">
          <n-gi>
            <n-button type="primary" :on-click="handleEdit.bind(null, {}, true)">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              添加租户
            </n-button>
          </n-gi>
          <n-gi class="moss-custom-table-param-end">
            <n-tooltip placement="top">
              <template #trigger>
                <n-icon>
                  <SyncOutlined class="moss-icon-action" @click="reloadTable" />
                </n-icon>
              </template>
              <span>刷新</span>
            </n-tooltip>
          </n-gi>
        </n-grid>
      </div>
      <n-spin :show="spinShow" size="small">
        <n-grid x-gap="12" :cols="4" v-if="dataSource.length > 0">
          <n-gi v-for="item in dataSource" :key="item.id">
            <TenantCard ref="tenantCardRef" :current="item" :reloadTable="reloadTable" @handleEdit="handleEdit" />
          </n-gi>
        </n-grid>
        <MossEmpty v-if="dataSource.length === 0" />
      </n-spin>
      <div class="custom-page">
        <n-pagination v-model:page="page" :page-count="pageCount" @change="handleChangePage" />
      </div>
    </n-card>

    <n-drawer v-model:show="showOuter" :width="720" @mask-click="resetForm" :mask-closable="false">
      <n-drawer-content :title="editTitle" :native-scrollbar="false">
        <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
          <n-divider title-placement="left">基本信息</n-divider>

          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="12" label="租户名称" path="tenant.tenantName">
              <n-input maxlength="150" show-count placeholder="请输入租户名称" v-model:value="formParams.tenant.tenantName" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="租户电话" path="tenant.tenantPhone">
              <n-input maxlength="20" show-count placeholder="请输入租户电话" v-model:value="formParams.tenant.tenantPhone" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="租户地址" path="tenant.tenantAddress">
              <n-cascader v-model:value="formParams.tenant.tenantAddress" placeholder="请选择" cascade :options="regions"
              label-field="cityName" value-field="mergerName"
                check-strategy="child" :show-path="true" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="详细地址" path="tenant.detailedAddress">
              <n-input maxlength="150" show-count placeholder="请输入详细地址" v-model:value="formParams.tenant.detailedAddress" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="租户邮箱" path="tenant.tenantEmail">
              <n-input maxlength="100" show-count placeholder="请输入租户邮箱" v-model:value="formParams.tenant.tenantEmail" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="统一社会信用代码" path="tenant.tenantCreditCode">
              <n-input maxlength="32" show-count placeholder="请输入统一社会信用代码"
                v-model:value="formParams.tenant.tenantCreditCode" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="行业类别" path="tenant.tenantIndustryType">
              <n-select v-model:value="formParams.tenant.tenantIndustryType" placeholder="请选择行业类别"
                :options="industryType" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="组织机构代码" path="tenant.tenantCode">
              <n-input maxlength="32" show-count placeholder="请输入组织机构代码" v-model:value="formParams.tenant.tenantCode" />
            </n-form-item-gi>
            <n-form-item-gi :span="24" label="租户简介" path="tenant.tenantDesc">
              <n-input maxlength="300" show-count type="textarea" :autosize="{
                minRows: 3,
                maxRows: 5
              }" v-model:value="formParams.tenant.tenantDesc" filterable placeholder="请输入租户简介" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="营业执照" path="tenant.tenantBusinessLicense">
              <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`" :headers="uploadHeaders"
                :data="{ type: 0 }" name="file" :width="100" :height="100"
                @upload-change="uploadTenantBusinessLicenseChange" v-model:value="tenantBusinessLicense" :maxNumber="1"
                helpText="单个文件不超过20MB，最多只能上传1个文件" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="门头照" path="tenant.tenantDoorPhoto">
              <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`" :headers="uploadHeaders"
                :data="{ type: 0 }" name="file" :width="100" :height="100" @upload-change="uploadTenantDoorPhotoChange"
                v-model:value="tenantDoorPhoto" :maxNumber="1" helpText="单个文件不超过20MB，最多只能上传1个文件" />
            </n-form-item-gi>
          </n-grid>

          <n-divider title-placement="left">法人信息</n-divider>
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="12" label="租户法人" path="tenantLegal.tenantUserId">
              <n-select v-model:value="formParams.tenantLegal.tenantUserId" filterable placeholder="请选择法人"
                :options="legalOptions" :loading="selectLoading" clearable remote @search="handleSearch" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="证件类型" path="tenantLegal.idType">
              <n-select v-model:value="formParams.tenantLegal.idType" placeholder="请选择证件类型" :options="documentType" />
            </n-form-item-gi>
            <n-form-item-gi :span="24" label="证件证件号" path="tenantLegal.idNumber">
              <n-input maxlength="32" show-count placeholder="请输入证件证件号" v-model:value="formParams.tenantLegal.idNumber" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="身份证人像面" path="tenantLegal.idCardUp">
              <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`" :headers="uploadHeaders"
                :data="{ type: 0 }" name="file" :width="100" :height="100" @upload-change="uploadIdCardUpChange"
                v-model:value="idCardUp" :maxNumber="1" helpText="单个文件不超过20MB，最多只能上传1个文件" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="身份证国徽面" path="tenantLegal.idCardDown">
              <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`" :headers="uploadHeaders"
                :data="{ type: 0 }" name="file" :width="100" :height="100" @upload-change="uploadIdCardDownChange"
                v-model:value="idCardDown" :maxNumber="1" helpText="单个文件不超过20MB，最多只能上传1个文件" />
            </n-form-item-gi>
            <n-form-item-gi :span="24" label="法人近照" path="tenantLegal.recentPhoto">
              <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`" :headers="uploadHeaders"
                :data="{ type: 0 }" name="file" :width="100" :height="100" @upload-change="uploadRecentPhotoChange"
                v-model:value="recentPhoto" :maxNumber="1" helpText="单个文件不超过20MB，最多只能上传1个文件" />
            </n-form-item-gi>
          </n-grid>
        </n-form>
        <template #footer>
          <n-space>
            <n-button @click="handleCloseDrawer">
              取消
            </n-button>
            <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">
              确定
            </n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, unref } from 'vue';
import { useMessage, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicUpload } from '@/components/Upload';
import { tenantPage, byTenantId, saveTenant, updateTenant } from '@/api/system/tenant';
import { regionTrees } from '@/api/system/region';
import { ResultEnum } from '@/enums/httpEnum';
import TenantCard from '../../../components/Custom/TenantCard.vue';
import { PlusOutlined, SyncOutlined } from '@vicons/antd';
import MossEmpty from '../../../components/Custom/MossEmpty.vue';
import { dictGroup } from '@/api/system/dict';
import { searchUser, usersById } from '@/api/system/user';
import { useGlobSetting } from '@/hooks/setting';
import { removeEmptyChildren } from '@/utils/convert';
import { useUser } from '@/store/modules/user';
const formRef: any = ref(null);
const tenantCardRef = ref();
const message = useMessage();
const editTitle = ref('');
const isAdd = ref(true);
const page = ref(1);
const pageCount = ref(1);
const dataSource: any = ref([]);
const spinShow = ref(false);
const industryType: any = ref([]);
const documentType: any = ref([]);
const regions: any = ref([]);
const showOuter = ref(false);
const globSetting = useGlobSetting();
const formBtnLoading = ref(false);
const userStore = useUser();
const selectLoading = ref(false);
const { uploadUrl } = globSetting;
const legalOptions: any = ref([]);
const defaultValueRef = () => ({
  tenant: {
    id: null,
    /*** 租户名称*/
    tenantName: '',
    /*** 租户地址*/
    tenantAddress: '',
    /*** 详细地址*/
    detailedAddress: '',
    /*** 租户电话*/
    tenantPhone: '',
    /*** 租户邮箱*/
    tenantEmail: '',
    /** * 营业执照*/
    tenantBusinessLicense: '',
    /*** 统一社会信用代码*/
    tenantCreditCode: '',
    /*** 门头照*/
    tenantDoorPhoto: '',
    /*** 行业类型*/
    tenantIndustryType: '',
    /*** 组织机构代码*/
    tenantCode: '',
    /*** 租户简介*/
    tenantDesc: '',
  },
  tenantLegal: {
    /** 租户法人用户ID */
    tenantUserId: '',
    /** 法人近照 */
    recentPhoto: '',
    /** 证件类型 */
    idType: '',
    /** 证件号 */
    idNumber: '',
    /** 身份证正面 */
    idCardUp: '',
    /** 身份证反面 */
    idCardDown: '',
  }
});
const rules: FormRules = {
  tenant: {
    tenantName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输租户名称',
    },
    tenantAddress: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择企业地址'
    },
    tenantPhone: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入企业电话',
    },
    tenantEmail: {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, trigger: ['blur', 'input'], message: '请输入正确的邮箱'
    },
  },
  tenantLegal: {
    tenantUserId: {
      type: 'number',
      required: true,
      trigger: ['blur', 'select'],
      message: '请选择企业法人',
    },
  }
};
let formParams = reactive(defaultValueRef());
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  {
    field: 'tenantName',
    component: 'NInput',
    label: '租户名称',
    componentProps: {
      placeholder: '请输入租户名称',
    },
  },
  {
    field: 'tenantPhone',
    component: 'NInput',
    label: '租户电话',
    componentProps: {
      placeholder: '请输入租户电话',
    },
  },
  {
    field: 'tenantEmail',
    component: 'NInput',
    label: '租户邮箱',
    componentProps: {
      placeholder: '请输入租户邮箱',
    },
  },
  {
    field: 'tenantIndustryType',
    component: 'NSelect',
    label: '行业类别',
    componentProps: {
      placeholder: '请选择行业类别',
      options: industryType,
    },
  },
];
const tenantBusinessLicense: any = ref([]);
const tenantDoorPhoto: any = ref([]);
const idCardUp: any = ref([]);
const idCardDown: any = ref([]);
const recentPhoto: any = ref([]);
const uploadHeaders = reactive({
  timestamp: new Date().getTime(),
  Authorization: 'Bearer ' + userStore.getToken,
});
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

const loadDataTable = async (res: any) => {
  spinShow.value = true;
  const data = await tenantPage({ ...getFieldsValue(), ...res });
  if (data.code === ResultEnum.SUCCESS) {
    page.value = data.data.current;
    pageCount.value = data.data.pages;
    dataSource.value = data.data.records;
    spinShow.value = false;
  } else {
    const resultMsg = data.data ? data.data : '';
    message.error(data.msg + '-' + resultMsg);
    spinShow.value = false;
  }
};
/**
 * 行业类别
 */
async function getIndustryTypes() {
  const data = await dictGroup({ dictGroup: 'Industry_type' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  industryType.value = arry;
}
/**
 *  证件类型
 */
const getDocumentTypes = async () => {
  const data = await dictGroup({ dictGroup: 'document_type' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  documentType.value = arry;
}
const apiRegionTrees = async () => {
  const data = await regionTrees({});
  const tree = removeEmptyChildren(data);
  regions.value = tree;
}
/**
 * 当前页发生改变
 * @param page 
 */
function handleChangePage(page) {
  loadDataTable({ current: page, size: 8 });
}
/**
 * 刷新表格
 */
function reloadTable() {
  loadDataTable({ current: page.value, size: 8 });
}
/**
 * 查询
 */
function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
/**
 * 新增编辑
 * @param current 
 * @param addStatus 
 */
async function handleEdit(current: any, addStatus: boolean) {
  showOuter.value = true;
  isAdd.value = addStatus;
  if (addStatus) {
    editTitle.value = `新增租户`;
  } else {
    editTitle.value = `编辑租${current.tenantName}`;
    // 企业信息
    const data = await byTenantId({ id: current.id });
    formParams = Object.assign(formParams, data);
    // 企业法人
    const users = await usersById({ id: data.tenantLegal.tenantUserId });
    let userList: any = [];
    userList.push({ label: users.name, value: users.id });
    legalOptions.value = userList;
    // 营业执照
    if (data.tenant.tenantBusinessLicense) {
      let license: any = [];
      license.push(data.tenant.tenantBusinessLicense);
      tenantBusinessLicense.value = license;
    }
    // 门头照
    if (data.tenant.tenantDoorPhoto) {
      let doorPhoto: any = [];
      doorPhoto.push(data.tenant.tenantDoorPhoto);
      tenantDoorPhoto.value = doorPhoto;
    }
    // 法人身份证人像面
    if (data.tenantLegal.idCardUp) {
      let cardUp: any = [];
      cardUp.push(data.tenantLegal.idCardUp);
      idCardUp.value = cardUp;
    }
    // 法人身份证国徽面
    if (data.tenantLegal.idCardDown) {
      let cardDown: any = [];
      cardDown.push(data.tenantLegal.idCardDown);
      idCardDown.value = cardDown;
    }
    // 法人近照
    if (data.tenantLegal.recentPhoto) {
      let legalrecentPhoto: any = [];
      legalrecentPhoto.push(data.tenantLegal.recentPhoto);
      recentPhoto.value = legalrecentPhoto;
    }
  }
}
/**
 * 关闭n-drawer
 */
function handleCloseDrawer() {
  showOuter.value = false;
  resetForm();
}
/**
 * 提交数据
 */
function confirmForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate(async (errors) => {
    if (!errors) {
      let data;
      if (isAdd.value === true) {
        data = await saveTenant(formParams);
      } else {
        data = await updateTenant(formParams);
      }
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        showOuter.value = false;
        resetForm();
        reloadTable();
      }
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}
function resetForm() {
  formRef.value.restoreValidation();
  formParams = Object.assign(unref(formParams), defaultValueRef());
  // 营业执照
  tenantBusinessLicense.value = [];
  // 门头照
  tenantDoorPhoto.value = [];
  // 法人身份证人像面
  idCardUp.value = [];
  // 法人身份证国徽面
  idCardDown.value = [];
  // 法人近照
  recentPhoto.value = [];
}
/**
 * 营业执照上传
 */
function uploadTenantBusinessLicenseChange(list: string[]) {
  tenantBusinessLicense.value = list;
  formParams.tenant.tenantBusinessLicense = list[0];
}
/**
 * 门头照上传
 */
function uploadTenantDoorPhotoChange(list: string[]) {
  tenantDoorPhoto.value = list;
  formParams.tenant.tenantDoorPhoto = list[0];
}
/**
 * 法人身份证人像面上传
 */
function uploadIdCardUpChange(list: string[]) {
  idCardUp.value = list;
  formParams.tenantLegal.idCardUp = list[0];
}
/**
 * 法人身份证国徽面上传
 */
function uploadIdCardDownChange(list: string[]) {
  idCardDown.value = list;
  formParams.tenantLegal.idCardDown = list[0];
}
/**
 * 法人近照上传
 */
function uploadRecentPhotoChange(list: string[]) {
  recentPhoto.value = list;
  formParams.tenantLegal.recentPhoto = list[0];
}
/**
 * 搜索法人
 */
async function handleSearch(query: string) {
  selectLoading.value = true;
  const data = await searchUser({ name: query });
  const arry = data.map(item => ({ label: item.name, value: item.id }));
  legalOptions.value = arry;
  selectLoading.value = false;
}
onMounted(() => {
  loadDataTable({ current: 1, size: 8 });
  getIndustryTypes();
  getDocumentTypes();
  apiRegionTrees();
})
</script>

<style lang="less" scoped>
.moss-custom-table-param {
  padding: 0px 0px 15px 0px;
}

.moss-custom-table-param-end {
  text-align: end;
}
</style>
